﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Pages_SectionBalanceReport : System.Web.UI.Page
{
	private string startText, endText;
	protected void Page_Load(object sender, EventArgs e)
	{
		string sectionId = Request.QueryString["Section"], sectionName;
		start.Text = Request.QueryString["SDT"];
		end.Text = Request.QueryString["EDT"];
		DateTime startDT = DateTime.Now, endDT = DateTime.Now;
		if ((sectionId == null) || string.IsNullOrEmpty(start.Text) || string.IsNullOrEmpty(end.Text) ||
			!DateTime.TryParse(start.Text, out startDT) || !DateTime.TryParse(end.Text, out endDT))
			Response.Redirect("SectionBalance.aspx?fromReport=true", true); //go select stuff
		//strIncludeTI = "1"
		Session["REGISTER_SECTION"] = sectionId;
		startText = Tools.GetDateInSql103Format(startDT);
		Session["REGISTER_SD"] = startDT.Date;
		Session["REGISTER_SH"] = startDT.Hour + ":" + startDT.Minute;
		endText = Tools.GetDateInSql103Format(endDT);
		Session["REGISTER_ED"] = endDT.Date;
		Session["REGISTER_EH"] = endDT.Hour + ":" + endDT.Minute;

		if (!sectionId.Equals("*"))
		{
			sectionName = Hipocrate.DB.DBConnection.GetData("Sections_Code",
				new string[] { "@sectionCode" },
				new object[] { sectionId.Equals("*") ? null : sectionId }).Tables[0].Rows[0]["Name"].ToString();
			target.Text = "sectia " + sectionName;
		}
		else
			target.Text = "sectii";

		ComputeStatistics(sectionId);
	}

	protected string GetHospitalName()
	{
		return Hipocrate.DB.DBConnection.GetData("SELECT DRG_Hospital_Name FROM DRG_HOSPITAL").Tables[0].Rows[0][0].ToString();
	}

	private void ComputeStatistics(string targetSection)
	{
		System.Data.DataTable dTable = Hipocrate.DB.DBConnection.GetData("Sections_Code",
			new string[] { "@sectionCode" },
			new object[] { targetSection.Equals("*") ? null : targetSection }).Tables[0];
		foreach (string colName in new string[] { "NrCrt", "nrPIcmFOCGValue", "icmFOCGValue",
				"nrPChronics", "chronicsValue", "nrPDaySpit", "dayValueSpit",
				"nrPReceVal", "receiptValue", "nrPTotal", "nrPValue",
				"chSalaries", "chIndirect", "foodExpenses", "drugsValue", "materialsValue",
				"drugsPNSValue", "materialsPNSValue", "chMaterials", "laboratoryValue", "othersValue",
				"chTotal", "rezTotal" })
			dTable.Columns.Add(colName);
		int rowIndex = 0, aux, nrPTotal;
		double value, runningTotal, final;
		foreach (System.Data.DataRow row in dTable.Rows)
		{
			string sectionId = row["Code"].ToString();
			row["NrCrt"] = ++rowIndex;

			nrPTotal = 0; runningTotal = 0;
			aux = GetICMFOCG(sectionId, out value);
			nrPTotal += aux; runningTotal += value;
			row["nrPIcmFOCGValue"] = aux;
			row["icmFOCGValue"] = value;
			aux = GetChronicsFOCG(sectionId, out value);
			nrPTotal += aux; runningTotal += value;
			row["nrPChronics"] = aux;
			row["chronicsValue"] = value;
			aux = GetDaySpitalization(sectionId, out value);
			nrPTotal += aux; runningTotal += value;
			row["nrPDaySpit"] = aux;
			row["dayValueSpit"] = value;
			aux = GetReceiptValue(sectionId, out value);
			nrPTotal += aux; runningTotal += value;
			row["nrPReceVal"] = aux;
			row["receiptValue"] = value;

			row["nrPTotal"] = nrPTotal;
			row["nrPValue"] = final = runningTotal;

			double chSalaries, chIndirect, chMaterials;
			GetFinancialExpenses(sectionId, out chSalaries, out chIndirect, out chMaterials);
			runningTotal = 0;
			row["chSalaries"] = chSalaries;
			runningTotal += chSalaries;
			row["chIndirect"] = chIndirect;
			runningTotal += chIndirect;
			row["foodExpenses"] = GetFoodExpenses(sectionId);
			row["drugsValue"] = value = GetDrugsValue(sectionId);
			runningTotal += value;
			row["materialsValue"] = value = GetMaterialsValue(sectionId);
			runningTotal += value;
			row["drugsPNSValue"] = GetDrugsPNSValue(sectionId);
			row["materialsPNSValue"] = GetMaterialsPNSValue(sectionId);
			row["chMaterials"] = chMaterials;
			runningTotal += chMaterials;
			row["laboratoryValue"] = value = GetLaboratoryValue(sectionId);
			runningTotal += value;
			row["othersValue"] = value = GetOthersValue(sectionId);
			runningTotal += value;
			row["chTotal"] = runningTotal; //chSalaries + chIndirect + drugsValue + materialsValue + chMaterials +laboratoryValue + othersValue
			final -= runningTotal;
			row["rezTotal"] = final;
		}
		allData.DataSource = dTable;
		allData.DataBind();
	}

	#region database access
	private double GetValue(string functionName, string sectionId, string columnName)
	{
		string sql = string.Format(" select * from {0}('{1}' ,'{2}' ,'{3}') ", functionName, startText, endText, sectionId);
		System.Data.DataTable dTable = Hipocrate.DB.DBConnection.GetData(sql).Tables[0];
		if (dTable.Rows.Count == 0)
		{
			//throw new ApplicationException("No rows coming from " + functionName);
			return 0;
		}
		return System.Convert.ToDouble(dTable.Rows[0][columnName]);
	}
	private int GetValues(string functionName, string sectionId, string columnName, string extraColumnName, out double secondResult)
	{
		string sql = string.Format(" select * from {0}('{1}' ,'{2}' ,'{3}') ", functionName, startText, endText, sectionId);
		System.Data.DataTable dTable = Hipocrate.DB.DBConnection.GetData(sql).Tables[0];
		if (dTable.Rows.Count == 0)
		{
			//throw new ApplicationException("No rows coming from " + functionName);
			secondResult = 0;
			return 0;
		}
		if (dTable.Columns.Contains(extraColumnName))
			secondResult = System.Convert.ToDouble(dTable.Rows[0][extraColumnName]);
		else
		{
			throw new ApplicationException("Cannot find Column '" + extraColumnName + "' in " + functionName);
			secondResult = double.NaN;
		}
		return System.Convert.ToInt32(dTable.Rows[0][columnName]);
	}
	private void GetFinancialExpenses(string sectionId, out double chSalaries, out double chIndirect, out double chMaterials)
	{
		string sql = string.Format(" select * from selCosts('{0}' ,'{1}' ,'{2}') ", startText, endText, sectionId);
		System.Data.DataTable dTable = Hipocrate.DB.DBConnection.GetData(sql).Tables[0];
		if (dTable.Rows.Count == 0)
		{
			//throw new ApplicationException("No rows coming from selCosts (GetFinancialExpenses)");
			chSalaries = chIndirect = chMaterials = 0;
			return;
		}
		chSalaries = System.Convert.ToDouble(dTable.Rows[0]["CheltuieliPersonal_1"]);
		chIndirect = System.Convert.ToDouble(dTable.Rows[0]["CheltuieliIndirecte_1"]);
		chMaterials = System.Convert.ToDouble(dTable.Rows[0]["CheltuieliDirecte_1"]);
	}
	#endregion

	protected double GetFoodExpenses(string strSection)
	{
		return GetValue("selFoodExpenses", strSection, "FoodValue");
	}
	protected int GetICMFOCG(string strSection, out double value)
	{
		return GetValues("selICMFOCG", strSection, "nrPatients", "TotalValue", out value);
	}
	protected int GetChronicsFOCG(string strSection, out double value)
	{
		return GetValues("selChronicsFOCG", strSection, "nrPatients", "ChronicValue", out value);
	}
	protected int GetDaySpitalization(string strSection, out double value)
	{
		return GetValues("selDayCheckins", strSection, "nrPatients", "dayValue", out value);
	}
	protected int GetReceiptValue(string strSection, out double value)
	{
		return GetValues("selReceipts", strSection, "nrPatients", "ExpTotal", out value);
	}
	//GetFinancialExpenses is in the "database access" region above
	protected double GetDrugsValue(string strSection)
	{
		return GetValue("selDrugsValue", strSection, "Value");
	}
	protected double GetMaterialsValue(string strSection)
	{
		return GetValue("selMaterialsValue", strSection, "Value");
	}
	protected double GetDrugsPNSValue(string strSection)
	{
		return GetValue("selDrugsPNSValue", strSection, "Value");
	}
	protected double GetMaterialsPNSValue(string strSection)
	{
		return GetValue("selMaterialsPNSValue", strSection, "Value");
	}
	protected double GetLaboratoryValue(string strSection)
	{
		return GetValue("selLaboratoryValue", strSection, "Value");
	}
	protected double GetOthersValue(string strSection)
	{
		return GetValue("selOthersValue", strSection, "Value");
	}
}
